package com.heima.wemedia.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaContans;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/1/26 15:48
 **/
@Service
@Transactional
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FastDFSClient fastDFSClient;
    @Value("${fdfs.url}")
    String fileServerUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 1. 检查参数
        if(multipartFile ==null || StringUtils.isEmpty(multipartFile.getOriginalFilename())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 将文件上传到fastDFS
        try {
            String fileId = fastDFSClient.uploadFile(multipartFile);
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(user.getId());
            wmMaterial.setUrl(fileId);
            wmMaterial.setType((short)0);
            wmMaterial.setIsCollection((short)0);
            wmMaterial.setCreatedTime(new Date());
            save(wmMaterial);
            wmMaterial.setUrl(fileServerUrl + fileId); // 为了前端回显  给图片加上前缀路径
            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件上传失败 ==> {}",e.getMessage());
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文件上传失败");
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1. 检查参数
        if(dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2. 封装条件   分页条件   查询条件
        Page<WmMaterial> pageRequest = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = Wrappers.<WmMaterial>lambdaQuery();
        if(dto.getIsCollected()!=null && dto.getIsCollected().equals(WemediaContans.COLLECT_MATERIAL)){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,WemediaContans.COLLECT_MATERIAL);
        }
        //3. 执行查询
        IPage<WmMaterial> pageResult = page(pageRequest, lambdaQueryWrapper);

        List<WmMaterial> list = pageResult.getRecords();
        list = list.stream().map((item) -> {  // 对每一个元素进行处理
            item.setUrl(fileServerUrl + item.getUrl()); // 添加前缀路径
            return item;
        }).collect(Collectors.toList()); // 将所有处理号的素材收集到一个新的集合中
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal());
        responseResult.setData(list);
        return responseResult;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Override
    public ResponseResult delPicture(Integer id) {
        // 1. 检查参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 判断这个素材有没有被引用
        Integer count = wmNewsMaterialMapper.selectCount(
                Wrappers.<WmNewsMaterial>lambdaQuery()
                        .eq(WmNewsMaterial::getMaterialId, id)
        );
        if(count!=null && count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前素材被引用不能删除");
        }
        // 获取当前登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 3. 根据id 和当前 登录用户ID 查询出素材
        WmMaterial wmMaterial = getOne(
                Wrappers.<WmMaterial>lambdaQuery()
                        .eq(WmMaterial::getId, id)
                        .eq(WmMaterial::getUserId, user.getId())
        );
        // 4. 根据素材获取文件的路径
        fastDFSClient.delFile(wmMaterial.getUrl());
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 1. 检查参数
        if(id == null || (!WemediaContans.CANCEL_COLLECT_MATERIAL.equals(type)&&!WemediaContans.COLLECT_MATERIAL.equals(type))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 根据ID 和 登录用户ID 进行收藏修改
        update(
                Wrappers.<WmMaterial>lambdaUpdate()
                        .set(WmMaterial::getIsCollection,type)
                        .eq(WmMaterial::getId,id)
                        .eq(WmMaterial::getUserId,user.getId())
        );
        return ResponseResult.okResult();
    }
}
